// 统一处理显示/隐藏的函数
function toggleSection(sectionId) {
    const currentSection = document.getElementById(sectionId);
    const otherSections = ['soldCars', 'unsoldCars', 'allCars', 'searchResult'].filter(id => id !== sectionId);

    // 切换当前部分
    currentSection.style.display = currentSection.style.display === 'block' ? 'none' : 'block';

    // 隐藏其他部分
    otherSections.forEach(id => {
        document.getElementById(id).style.display = 'none';
    });
}

// 添加状态记录变量
let lastSearchId = null;
let isSearchResultVisible = false;
let lastFilterConditions = null;
let isFilterResultVisible = false;

// 通过ID查询功能（添加切换逻辑）
document.getElementById('searchById').addEventListener('click', function () {
    const id = document.getElementById('searchId').value.trim();
    const resultContainer = document.getElementById('searchResult');

    if (!id) {
        alert('请输入车辆ID');
        return;
    }

    // 相同ID时的切换逻辑
    if (id === lastSearchId) {
        resultContainer.style.display = isSearchResultVisible ? 'none' : 'block';
        isSearchResultVisible = !isSearchResultVisible;
        return;
    }

    // 新ID请求逻辑
    axios.get(`/selectacar?cid=${id}`, {
        headers: {'User-Type': 'Admin'}
    })
        .then(response => {
            lastSearchId = id;
            isSearchResultVisible = true;

            const cars = response.data;
            let resultHtml;
            if (cars && cars.length > 0) {
                const car = cars[0];
                resultHtml = `
                <div class="search-result-item">
                    <h4>查询结果</h4>
                    <p>ID: ${car.cid}</p>
                    <p>品牌: ${car.cname}</p>
                    <p>颜色: ${car.color}</p>
                    <p>价格: ${car.price}</p>
                    <p>状态: ${car.status === 1 ? '已售出' : '未售出'}</p>
                    ${car.time ? `<p>售出/入库时间: ${car.time}</p>` : ''}
                </div>
            `;
            } else {
                resultHtml = `
                <div class="search-result-item error">
                    未找到对应车辆信息
                </div>
            `;
            }

            resultContainer.innerHTML = resultHtml;
            resultContainer.style.display = 'block';
        })
        .catch(err => {
            resultContainer.innerHTML = `
            <div class="search-result-item error">
                请求失败，请稍后重试
            </div>
        `;
            resultContainer.style.display = 'block';
            lastSearchId = null;
            isSearchResultVisible = false;
        });
});

// 查询已售出车辆
let soldCarsData = [];
let unsoldCarsData = [];
let allCarsData = [];

// 查询已售出车辆
document.getElementById('querySoldCars').onclick = function () {
    const container = document.getElementById('soldCars');

    if (soldCarsData.length === 0) {
        axios.get('/sselectcarall', {
            headers: {'User-Type': 'Admin'}
        }).then(response => {
            soldCarsData = response.data;
            container.innerHTML = `
                <h3>已售出车辆：</h3>
                <ul>${
                soldCarsData.map(car => `
                        <li>id: ${car.cid}, 品牌: ${car.cname}, 
                        颜色: ${car.color}, 价格: ${car.price}, 
                        时间: ${car.time}, 状态: 已售出</li>`
                ).join('')
            }</ul>
            `;
            toggleSection('soldCars');
        }).catch(err => alert('错误: ' + err.response.data));
    } else {
        toggleSection('soldCars');
    }

    // 隐藏高级筛选框和其他数据区域
    document.getElementById('searchResult').style.display = 'none';
    document.getElementById('unsoldCars').style.display = 'none';
    document.getElementById('allCars').style.display = 'none';
    document.getElementById('viewCarsSection').style.display = 'block';
};

// 查询未售出车辆
document.getElementById('queryUnsoldCars').onclick = function () {
    const container = document.getElementById('unsoldCars');

    if (unsoldCarsData.length === 0) {
        axios.get('/unselectcarall', {
            headers: {'User-Type': 'Admin'}
        }).then(response => {
            unsoldCarsData = response.data;
            container.innerHTML = `
                <h3>未售出车辆：</h3>
                <ul>${
                unsoldCarsData.map(car => `
                        <li>id: ${car.cid}, 品牌: ${car.cname}, 
                        颜色: ${car.color}, 价格: ${car.price}, 
                        时间: ${car.time}, 状态: 未售出</li>`
                ).join('')
            }</ul>
            `;
            toggleSection('unsoldCars');
        }).catch(err => alert('错误: ' + err.response.data));
    } else {
        toggleSection('unsoldCars');
    }

    // 隐藏高级筛选框和其他数据区域
    document.getElementById('searchResult').style.display = 'none';
    document.getElementById('soldCars').style.display = 'none';
    document.getElementById('allCars').style.display = 'none';
    document.getElementById('viewCarsSection').style.display = 'block';
};

// 查询所有车辆
document.getElementById('queryAllCars').onclick = function () {
    const container = document.getElementById('allCars');

    if (allCarsData.length === 0) {
        axios.get('/selectcarall', {
            headers: {'User-Type': 'Admin'}
        }).then(response => {
            allCarsData = response.data;
            container.innerHTML = `
                <h3>所有车辆：</h3>
                <ul>${
                allCarsData.map(car => `
                        <li>id: ${car.cid}, 品牌: ${car.cname}, 
                        颜色: ${car.color}, 价格: ${car.price}, 
                        时间: ${car.time}, 状态: 
                        <span style="color:white">${
                        car.status ? '已售出' : '未售出'
                    }</span></li>`
                ).join('')
            }</ul>
            `;
            toggleSection('allCars');
        }).catch(err => alert('错误: ' + err.response.data));
    } else {
        toggleSection('allCars');
    }

    // 隐藏高级筛选框和其他数据区域
    document.getElementById('searchResult').style.display = 'none';
    document.getElementById('soldCars').style.display = 'none';
    document.getElementById('unsoldCars').style.display = 'none';
    document.getElementById('viewCarsSection').style.display = 'block';
};

// 筛选功能
document.getElementById('applyFilter').addEventListener('click', function () {
    // 获取所有车辆数据
    if (allCarsData.length === 0) {
        alert('请先查询所有车辆数据');
        return;
    }

    // 获取筛选条件
    const idStart = parseInt(document.getElementById('idRangeStart').value) || null;
    const idEnd = parseInt(document.getElementById('idRangeEnd').value) || null;
    const cname = document.getElementById('cname').value.trim();
    const color = document.getElementById('color').value.trim();
    const priceStart = parseFloat(document.getElementById('priceRangeStart').value) || null;
    const priceEnd = parseFloat(document.getElementById('priceRangeEnd').value) || null;
    const timeStart = document.getElementById('timeRangeStart').value || null;
    const timeEnd = document.getElementById('timeRangeEnd').value || null;

    // 构造当前筛选条件对象
    const currentFilterConditions = {
        idStart, idEnd, cname, color, priceStart, priceEnd, timeStart, timeEnd
    };

    // 如果当前筛选条件与上次相同，则切换显示/隐藏
    if (JSON.stringify(currentFilterConditions) === JSON.stringify(lastFilterConditions)) {
        const filterResultContainer = document.getElementById('searchResult');
        filterResultContainer.style.display = isFilterResultVisible ? 'none' : 'block';
        isFilterResultVisible = !isFilterResultVisible;
        return;
    }

    // 如果是新的筛选条件，则执行筛选逻辑
    lastFilterConditions = currentFilterConditions;
    isFilterResultVisible = true;

    // 筛选逻辑
    const filteredCars = allCarsData.filter(car => {
        // ID区间筛选
        if (idStart !== null && car.cid < idStart) return false;
        if (idEnd !== null && car.cid > idEnd) return false;

        // 品牌筛选
        if (cname && car.cname && !car.cname.includes(cname)) return false;

        // 颜色筛选
        if (color && car.color && !car.color.includes(color)) return false;

        // 价格区间筛选
        if (priceStart !== null && car.price < priceStart) return false;
        if (priceEnd !== null && car.price > priceEnd) return false;

        // 时间区间筛选
        if (timeStart && car.time && new Date(car.time) < new Date(timeStart)) return false;
        if (timeEnd && car.time && new Date(car.time) > new Date(timeEnd)) return false;

        return true;
    });

    // 显示筛选结果
    const filterResultContainer = document.getElementById('searchResult');
    if (filteredCars.length > 0) {
        filterResultContainer.innerHTML = `
            <h3>筛选结果（共 ${filteredCars.length} 辆）</h3>
            <ul>${
            filteredCars.map(car => `
                    <li>ID: ${car.cid}, 品牌: ${car.cname}, 
                        颜色: ${car.color || '无'}, 
                        价格: ${car.price}, 时间: ${car.time || '无'}, 
                        状态: ${car.status ? '已售出' : '未售出'}</li>`
            ).join('')
        }</ul>
        `;
    } else {
        filterResultContainer.innerHTML = `
            <div class="search-result-item error">
                没有找到符合条件的车辆
            </div>
        `;
    }

    filterResultContainer.style.display = 'block';

    // 隐藏其他数据区域
    document.getElementById('soldCars').style.display = 'none';
    document.getElementById('unsoldCars').style.display = 'none';
    document.getElementById('allCars').style.display = 'none';
    document.getElementById('viewCarsSection').style.display = 'block';
});

// 重置筛选条件
document.getElementById('resetFilter').addEventListener('click', function () {
    document.getElementById('idRangeStart').value = '';
    document.getElementById('idRangeEnd').value = '';
    document.getElementById('cname').value = '';
    document.getElementById('color').value = '';
    document.getElementById('priceRangeStart').value = '';
    document.getElementById('priceRangeEnd').value = '';
    document.getElementById('timeRangeStart').value = '';
    document.getElementById('timeRangeEnd').value = '';

    // 收起高级筛选的数据框
    document.getElementById('searchResult').style.display = 'none';
});